﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace 测试项目
{
    class Program
    {


        //获取当前程序相关的一些路径信息
        public static string AppPath = AppDomain.CurrentDomain.BaseDirectory;

        public static string ConfigPathBase = AppDomain.CurrentDomain.BaseDirectory + "Config";

        public static string ConfigPath = AppDomain.CurrentDomain.BaseDirectory + "Config\\config.ini";

        public static string ParamSystemPath = AppDomain.CurrentDomain.BaseDirectory + "ParamSystem";

        public static string ConfigInfoPath = AppDomain.CurrentDomain.BaseDirectory + "ParamConfig";

        public static string PLCSignalPath = AppDomain.CurrentDomain.BaseDirectory + "PLCSignalConfig";

        public static string AppLogPath = AppDomain.CurrentDomain.BaseDirectory + "Log";

        public static string PinterPath = AppDomain.CurrentDomain.BaseDirectory + "Printer";

        public static string StringRulesPath = AppDomain.CurrentDomain.BaseDirectory + "StringRules";

        public static string MesCconfigPath = AppDomain.CurrentDomain.BaseDirectory + "Config\\mes.ini";

        public static string StatisticsPath = AppDomain.CurrentDomain.BaseDirectory + "Config\\ProductStatistics.ini";


        public void method1()
        {

            Console.WriteLine(AppPath);
            Console.WriteLine(ConfigPathBase);
            Console.WriteLine(ConfigPath);
            Console.WriteLine(ParamSystemPath);
            Console.WriteLine(ConfigInfoPath);
            Console.WriteLine(PLCSignalPath);
            Console.WriteLine(AppLogPath);
            Console.WriteLine(PinterPath);
            Console.WriteLine(StringRulesPath);
            Console.WriteLine(MesCconfigPath);
            Console.WriteLine(StatisticsPath);




            string bordInfos = "hello,";
            Console.WriteLine(bordInfos);


            //去除小板信息末尾多余的逗号
            int index = bordInfos.LastIndexOf(",");
            bordInfos = bordInfos.Substring(0, index);
            Console.WriteLine(bordInfos);

            //获取操作系统平台名称
            string os = Environment.OSVersion.Platform.ToString();
            Console.WriteLine("操作系统名称: " + os);

            Console.WriteLine(MethodInfo.GetCurrentMethod().ToString());
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodInfo.GetCurrentMethod().Name);










            string st = new StackTrace(0, true).GetFrame(0).GetFileLineNumber().ToString();

            Console.WriteLine(getNameSpaceClassMethodName());


        }

        //返回当前程序行号
        public static string getNameSpaceClassMethodName()
        {

            return System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodInfo.GetCurrentMethod().Name + new StackTrace(0, true).GetFrame(0).GetFileLineNumber().ToString();
        }
        public void method2()
        {
            string text = "";
            char value = 'E';
            int num = Convert.ToInt32(value);
            Console.WriteLine(num);
            for (int i = 0; i < 24; i++)
            {
                num += i;
                text = Convert.ToChar(num).ToString();
            }

            Console.WriteLine(text.ToString());
        }


        //定义委托
        public delegate void pt(int a, int b);
        //定义事件
        public event pt PT;

        //定义方法
        public void pp(int a, int b)
        {
            Console.WriteLine((a + b));
        }

        //委托与事件测试
        public void method4()
        {

            Program p = new Program();
            pt a = new pt(p.pp);
            p.PT = a;
            p.PT(34, 55);

            p.PT = p.pp;
            p.PT(34, 55);

            string EXE = Assembly.GetExecutingAssembly().GetName().Name;
            string Path; //存储路径
            string IniPath = System.Environment.CurrentDirectory;
            Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;

            //输出当前可执行文件的完整路径：C:\Users\AUTO\Desktop\测试项目\测试项目\bin\Debug
            Console.WriteLine(Path);
            Console.WriteLine(EXE);

        }


        private static void HeartBeatLoop()
        {


            int nHeart = 0;
            int nLastHeart = 0;
            int SleepTime = 5000;
            while (true)
            {


                #region ------------------------心跳信号修改 20230719-----------------------------
                nHeart = Environment.TickCount - nLastHeart;
                if (false)
                {
                    Console.WriteLine(string.Format("心跳信号正常，采集信号周期时间为:{0} ms", SleepTime));
                }
                else
                {
                    Console.WriteLine(string.Format("心跳信号异常，等待时间已超出:{0} ms", nHeart > SleepTime ? SleepTime + 100 : SleepTime));
                }
                nLastHeart = Environment.TickCount;
                //5s收集一次PLC心跳信号
                Thread.Sleep(SleepTime);
                #endregion

            }


        }

        public void dfff()
        {
            StackFrame sf = st.GetFrame(0);
            Console.WriteLine(" File: {0}", sf.GetFileName());                                                //文件名
            Console.WriteLine(" Method: {0}", sf.GetMethod().Name);                                 //函数名
            Console.WriteLine(" Line Number: {0}", sf.GetFileLineNumber());                  //文件行号
            Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());


        }

        static StackTrace st = new StackTrace(new StackFrame(true));


        public static string GetFixCmd(string cmdChar, int startChanel, int endChanel)
        {
            string cmd = string.Empty;
            for (int i = startChanel; i <= endChanel; i++)
            {
                cmd = string.Format("{0}{1},{2};", cmd, i, cmdChar);
            }
            return cmd;
        }

        private static string CheckSum(string data)
        {
            byte sum = 0x00;
            for (int i = 0; i < data.Length; i++)
            {
                sum += (byte)(data[i]);
            }
            return string.Format("{0:X2}", (byte)(0xFF - sum)).ToUpper();
        }

        static ConcurrentQueue<string> WPSignalQueue = new ConcurrentQueue<string>();


        private void fileLook()
        {
            FileSystemWatcher watcher = new FileSystemWatcher(@"D:\");
            watcher.NotifyFilter = NotifyFilters.Attributes
                                 | NotifyFilters.CreationTime
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.FileName
                                 | NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.Security
                                 | NotifyFilters.Size;

            watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            watcher.Deleted += OnDeleted;
            watcher.Renamed += OnRenamed;
            watcher.Error += OnError;

            watcher.Filter = "test.ini";
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("Press enter to exit.");

        }

        public void terss()
        {
            string path = Directory.GetCurrentDirectory() + "/Station.json";
            string data = string.Empty;

            //ConcurrentDictionary<int, WorkDataItem> dictionary = new ConcurrentDictionary<int, WorkDataItem>();
            //for (int i = 20; i < 30; i++)
            //{
            //    WorkDataItem item = new WorkDataItem() { 主条码 = i.ToString(), 时间 = DateTime.Now.ToString(), 上传结果 = "pass", 不良信息 = "无结果", 档位 = "4", 电芯分选通道号 = "4", 电芯内阻 = "0.289", 电芯电压 = "3.98" };
            //    dictionary.TryAdd(i, item);
            //}

            //DictionarySerialize(dictionary, path, ref data);
            //Console.WriteLine(data);



            ConcurrentDictionary<int, WorkDataItem> cd = new ConcurrentDictionary<int, WorkDataItem>();
            cd = DictionaryDeserialize(path, ref data);
            Console.WriteLine(data);
            foreach (var item in cd)
            {
                WorkDataItem wd = item.Value;
                string wddata = JsonConvert.SerializeObject(wd);
                Console.WriteLine(item.Key + ":" + wddata);
            }
        }

        static void Main()
        {



            Console.ReadLine();
        }

        /// <summary>
        /// 序列化为字典
        /// </summary>
        /// <param name="dictionary">需要序列化的字典</param>
        /// <param name="path">字典序列化信息保存路径</param>
        /// <param name="msg">执行信息</param>
        /// <returns>返回反序列化字典成功返回true，否则返回false</returns>
        public static bool DictionarySerialize(ConcurrentDictionary<int, WorkDataItem> dictionary, string path, ref string msg)
        {
            bool flag = false;
            string json = JsonConvert.SerializeObject(dictionary);
            try
            {
                if (!string.IsNullOrEmpty(json))
                {
                    File.WriteAllText(path, json);
                    flag = true;
                    msg = string.Format("函数{0}执行成功，生产数据=====【{1}】=====序列化保存完成！！", nameof(DictionarySerialize), json);
                }

            }
            catch (Exception e)
            {
                msg = string.Format("函数{0}执行失败，生产数据=====【{1}】=====序列化保存失败，错误信息{2}！！", nameof(DictionarySerialize), json, e.Message);
            }


            return flag;
        }

        /// <summary>
        /// 序列化字典
        /// </summary>
        /// <param name="path">序列化字典字符串的保存路径</param>
        /// <param name="msg">执行信息</param>
        /// <returns>返回字典，若反序列失败则返回空字典</returns>
        public static ConcurrentDictionary<int, WorkDataItem> DictionaryDeserialize(string path, ref string msg)
        {
            ConcurrentDictionary<int, WorkDataItem> dic = new ConcurrentDictionary<int, WorkDataItem>();
            string data = string.Empty;
            try
            {
                data = File.ReadAllText(path);
                dic = JsonConvert.DeserializeObject<ConcurrentDictionary<int, WorkDataItem>>(data);
                if (!string.IsNullOrEmpty(data) && dic.Count > 0)
                {
                    msg = string.Format("函数{0}执行成功，生产数据=====【{1}】=====反序列化保存完成！！", nameof(DictionaryDeserialize), data);
                }


            }
            catch (Exception e)
            {
                msg = string.Format("函数{0}执行失败，生产数据=====【{1}】=====反序列化保存失败，错误信息{2}！！", nameof(DictionarySerialize), data, e.Message);
            }

            return dic;
        }




        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType != WatcherChangeTypes.Changed)
            {
                return;
            }
            Console.WriteLine("Changed: {e.FullPath}");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            string value = "Created: {e.FullPath}";
            Console.WriteLine(value);
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Deleted: {e.FullPath}");
        }

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("Renamed:");
            Console.WriteLine("    Old: {e.OldFullPath}");
            Console.WriteLine("    New: {e.FullPath}");
        }

        private static void OnError(object sender, ErrorEventArgs e)
        { PrintException(e.GetException()); }

        private static void PrintException(Exception ex)
        {
            if (ex != null)
            {
                Console.WriteLine("Message: {ex.Message}");
                Console.WriteLine("Stacktrace:");
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine();
                PrintException(ex.InnerException);
            }
        }
    }



    [Serializable]
    //TODO:可通知实时数据定义
    public class WorkDataItem : NotifyClassBase
    {
        #region——私有变量——
        public string BarCodeID;
        public string IRResult;
        public string VResult;
        private string MainCode;
        private string IR;
        private string V;
        public string Chanel;
        private string GearName;
        private string GearChanel;
        private string TestResult;
        private string UploadResult;
        private string UploadTime;
        private string DefectiveInfo;
        #endregion

        #region——公用函数——
        public virtual void Clear()
        {
            BarCodeID = "";
            MainCode = "";
            Chanel = "";
            GearName = "";
            GearChanel = "";
            V = "";
            IR = "";
            TestResult = "";
            UploadResult = "";
            DefectiveInfo = "";
            UploadTime = DateTime.Now.ToString();

        }
        /// <summary>
        /// 因后面用到泛型，默认构造函数的所有字段都必须初始化
        /// </summary>
        public WorkDataItem()
        {
            BarCodeID = "";
            MainCode = "";
            Chanel = "";
            GearName = "";
            GearChanel = "";
            V = "";
            IR = "";
            TestResult = "";
            UploadResult = "";
            DefectiveInfo = "";
            UploadTime = DateTime.Now.ToString(); ;

        }
        #endregion

        #region——公共属性——

        public string 主条码
        {
            get { return MainCode; }
            set
            {
                if (value != MainCode)
                {
                    MainCode = value;
                    NotifyPropertyChanged("主条码");
                }
            }
        }

        public string 电芯分选通道号
        {
            get { return Chanel; }
            set
            {
                if (value != Chanel)
                {
                    Chanel = value;
                    NotifyPropertyChanged("电芯分选通道号");
                }
            }
        }
        public string 电芯电压
        {
            get { return V; }
            set
            {
                if (value != V)
                {
                    V = value;
                    NotifyPropertyChanged("电芯电压");
                }
            }
        }
        public string 电芯内阻
        {
            get { return IR; }
            set
            {
                if (value != IR)
                {
                    IR = value;
                    NotifyPropertyChanged("电芯内阻");
                }
            }
        }

        public string 档位
        {
            get { return GearName; }
            set
            {
                if (value != GearName)
                {
                    GearName = value;
                    NotifyPropertyChanged("档位");
                }
            }
        }

        public string 档位通道
        {
            get { return GearChanel; }
            set
            {
                if (value != GearChanel)
                {
                    GearChanel = value;
                    NotifyPropertyChanged("档位通道");
                }
            }
        }



        public string 测试结果
        {
            get { return TestResult; }
            set
            {
                if (value != TestResult)
                {
                    TestResult = value;
                    NotifyPropertyChanged("测试结果");
                }
            }
        }
        public string 上传结果
        {
            get { return UploadResult; }
            set
            {
                if (value != UploadResult)
                {
                    UploadResult = value;
                    NotifyPropertyChanged("上传结果");
                }
            }
        }
        public string 不良信息
        {
            get { return DefectiveInfo; }
            set
            {
                if (value != DefectiveInfo)
                {
                    DefectiveInfo = value;
                    NotifyPropertyChanged("不良信息");
                }
            }
        }
        public string 时间
        {
            get { return UploadTime; }
            set
            {
                if (value != UploadTime)
                {
                    UploadTime = value;
                    NotifyPropertyChanged("时间");
                }
            }
        }

        #endregion
    }



    [Serializable]
    public class NotifyClassBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }


    public interface res
    {
        public void test();
    }


    public class resDemo : res
    {
             
     
    }
}

